﻿# -*-coding: UTF-8 -*-
from Clover.CloverSystem import CloverSystem
from Clover.EngineSystemFactory import register_engine_module
from Clover.TimerSystem.Timer import RepeatTimer, DelayTimer


@register_engine_module
class TimerSystem(CloverSystem):
	def __init__(self, engine):
		super().__init__(engine)
		self.running_timers = []  # 正在运行的定时器
		self.timer_table = {}  # timer_id -> timer 的映射
		self.need_remove_timers = []  # 需要移除的定时器
		self.timer_counter = 0  # 用于生成唯一ID

		# 对象池 - 使用类作为key，存储闲置的定时器
		self.idle_timers = {
			RepeatTimer: [],
			DelayTimer: []
		}

		# 设置最大池大小，防止无限增长
		self.max_pool_size = 50

	def tick(self, delta_time):
		self.need_remove_timers.clear()

		# 只遍历运行中的定时器
		for timer in self.running_timers:
			if not timer.tick(delta_time):
				continue
			# 如果tick返回True，表示定时器需要被移除
			self.need_remove_timers.append(timer)

		# 移除需要删除的定时器
		for timer in self.need_remove_timers:
			self.running_timers.remove(timer)
			# 从timer_table中移除对应的定时器
			self.remove_from_timer_table(timer)
			# 将定时器返回到对象池
			self.return_timer_to_pool(timer)

	def generate_timer_id(self):
		"""生成唯一的定时器ID"""
		self.timer_counter += 1
		return f"timer_{self.timer_counter}"

	def get_timer_from_pool(self, timer_class):
		"""从对象池获取定时器，如果池为空则创建新实例"""
		pool = self.idle_timers.get(timer_class, [])
		if pool:
			return pool.pop()
		else:
			# 如果池为空，创建新的定时器
			return timer_class()

	def return_timer_to_pool(self, timer):
		"""将定时器返回到对象池"""
		timer_class = type(timer)
		pool = self.idle_timers.get(timer_class, [])

		# 如果池大小未超过限制，则将定时器重置并放回池中
		if len(pool) < self.max_pool_size:
			timer.reset()
			pool.append(timer)
			self.idle_timers[timer_class] = pool

	def register_repeat_timer(self, repeat_interval_seconds, function, *args, **kwargs):
		timer_id = self.generate_timer_id()
		# 从对象池获取定时器并设置参数
		repeat_timer = self.get_timer_from_pool(RepeatTimer)
		repeat_timer.setup(timer_id, repeat_interval_seconds)
		repeat_timer.set_callback(function, *args, **kwargs)

		self.running_timers.append(repeat_timer)
		# 添加到timer_table
		self.timer_table[timer_id] = repeat_timer
		return timer_id

	def cancel_timer(self, timer_id):
		"""通过ID取消定时器"""
		if timer_id in self.timer_table:
			timer = self.timer_table.pop(timer_id)
			timer.cancel()
			# 立即从running_timers列表中移除
			if timer in self.running_timers:
				self.running_timers.remove(timer)
			# 将定时器返回到对象池
			self.return_timer_to_pool(timer)
			return True
		return False

	def register_delay_exec(self, delay_seconds, function, *args, **kwargs):
		timer_id = self.generate_timer_id()
		# 从对象池获取定时器并设置参数
		delay_timer = self.get_timer_from_pool(DelayTimer)
		delay_timer.setup(timer_id, delay_seconds)
		delay_timer.set_callback(function, *args, **kwargs)

		self.running_timers.append(delay_timer)
		# 延迟定时器也需要添加到timer_table，以便可以通过ID取消
		self.timer_table[timer_id] = delay_timer
		return timer_id

	def remove_from_timer_table(self, timer):
		"""从timer_table中移除定时器"""
		if timer.timer_id in self.timer_table:
			del self.timer_table[timer.timer_id]

	def get_active_timer_count(self):
		"""获取活跃定时器数量（用于调试）"""
		return len(self.running_timers)

	def get_registered_timer_ids(self):
		"""获取所有注册的定时器ID（用于调试）"""
		return list(self.timer_table.keys())

	def is_timer_active(self, timer_id):
		"""检查指定ID的定时器是否活跃"""
		if timer_id in self.timer_table:
			timer = self.timer_table[timer_id]
			return timer.active and timer in self.running_timers
		return False

	def get_pool_stats(self):
		"""获取对象池统计信息（用于调试）"""
		return {
			"repeat_timer_pool": len(self.idle_timers[RepeatTimer]),
			"delay_timer_pool": len(self.idle_timers[DelayTimer]),
			"active_timers": len(self.running_timers)
		}

	def clear_all_timers(self):
		"""清除所有定时器（用于重置场景等）"""
		# 取消所有活跃定时器
		for timer_id in list(self.timer_table.keys()):
			self.cancel_timer(timer_id)

		# 清空活跃定时器列表
		self.running_timers.clear()
		self.timer_table.clear()
		self.need_remove_timers.clear()
